package com.txy.domain.strategy.service.rule.tree.impl;

import com.txy.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import com.txy.domain.strategy.model.vo.StrategyAwardStockVO;
import com.txy.domain.strategy.repository.IStrategyRepository;
import com.txy.domain.strategy.service.armory.IStrategyDispatch;
import com.txy.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.txy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultTreeFactory.DecisionEngineRes logic(Long strategyId, String userId, Integer awardId, String ruleValue) {
        log.info("规则过滤-规则树-rule_stock开始: strategyId={}, userId={}", strategyId, userId);
        // 如果能减少库存
        if (strategyDispatch.subtractionAwardStock(strategyId, awardId)) {

            // 发送延迟队列 由定时任务拉取队列中的抽奖奖品刷新数据库
            log.info("发送延迟队列：{}", awardId);
            repository.sendQueue(StrategyAwardStockVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId).build());

            log.info("规则过滤-规则树-rule_stock接管，库存充足: strategyId={}, userId={}", strategyId, userId);
            // 库存接管
            return DefaultTreeFactory.DecisionEngineRes.builder()
                    .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.TAKE_OVER)
                    .awardResClass(DefaultTreeFactory.AwardResClass.builder()
                            .awardId(awardId).build()).build();
        }

        log.info("规则过滤-规则树-rule_stock放行，库存不够: strategyId={}, userId={}", strategyId, userId);
        // 返回幸运奖
        return DefaultTreeFactory.DecisionEngineRes.builder()
                .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.ALLOW).build();
    }
}
